package com.jch.netty_client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DemoClientHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接信息：" + ctx.channel().localAddress().toString());
        String msg = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 客户端连接服务端成功！\r\n";
        ctx.writeAndFlush(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开连接：" + ctx.channel().localAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String msgDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
        System.out.println(msgDate + " 客户端收到消息：" + msg);
        String clientMsg = msgDate + " 客户端收到消息：" + msg + "\r\n";
        ctx.writeAndFlush(clientMsg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息：" + cause.getMessage());
    }
}
